<template>
  <view>
    <view>
      <view class='header'>
        <image src='https://www.linqinghu.cn/ruixiang/static/img/ruixianglogo.jpg'></image>
      </view>

      <view class='content'>
        <view>申请获取以下权限</view>
        <text>获得你的公开信息(昵称，头像等)</text>
      </view>
      <!-- #ifdef APP-PLUS -->
      <button class='bottom' type="primary" @tap="getUserInfo">获取用户信息</button>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN -->
      <button class='bottom' type="primary" open-type="getUserInfo" @getuserinfo="wxGetUserInfo">授权登录</button>
      <!-- #endif -->
    </view>
  </view>
</template>

<script>
  import {URI_POSTUSERINFO,URI_LOGIN} from "../../utils/api";

  export default {
    name: "login",
    data(){
      return {}
    },
    methods:{
      getUserInfo(){
        console.log('app');
      },
      wxGetUserInfo(e){
        console.log("得到用户信息", e);
        if(e.detail.errMsg !== 'getUserInfo:ok'){
          uni.showModal({
            title:"获取用户信息失败",
            content:"错误原因"+e.detail.errMsg,
            showCancel:false
          });
          return;
        }
        let userInfo =  e.detail.userInfo;
        uni.setStorageSync('userInfo',userInfo);
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            let code = res.code;

            this.$ajax.post(URI_LOGIN,{
              code:code,
            }).then(res=>{
              uni.setStorageSync('access_token',res.data.access_token);
              uni.setStorageSync('userId',res.data.id);
              this.$ajax.post(URI_POSTUSERINFO,{
                ...userInfo,
                access_token:res.data.access_token,
                userId:res.data.id
              }).then(res=>{
                console.log(res);
                uni.showModal({
                  title: '温馨提示',
                  content: '授权登录成功！',
                  showCancel: false,
                  confirmColor: '#ff474f',
                  success: function (res) {
                    if (res.confirm) {
                      wx.navigateBack({
                        delta: 1,
                      });
                    }
                  }
                })
              })
            })
          }
        })
      },
    }
  }
</script>

<style>

  page{
    background: #fff;
  }

  .header {
    margin: 90upx 0 90upx 50upx;
    border-bottom: 1px solid #ccc;
    text-align: center;
    width: 650upx;
    height: 300upx;
    line-height: 450upx;
  }

  .header image {
    width: 200upx;
    height: 200upx;
    border-radius: 100px;
  }

  .content {
    margin-left: 50upx;
    margin-bottom: 90upx;
  }

  .content text {
    display: block;
    color: #9d9d9d;
    margin-top: 40upx;
  }

  .bottom {
    border-radius: 80upx;
    margin: 70upx 50upx;
    font-size: 35upx;
  }
</style>